package cn.cuilan.secondkill.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Jedis接口模板，防止忘记释放jedis连接资源
 */
public class JedisTemplate {

    private JedisPool jedisPool;

    public JedisTemplate(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public <T> T execute(JedisHandler<T> handler) {
        T result;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result = handler.handler(jedis);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return result;
    }

    public interface JedisHandler<T> {
        T handler(Jedis jedis);
    }
}
